package request

import (
	"awesomeProject2/src/test2020/stats/constant"
	"awesomeProject2/src/test2020/stats/parse"
	"github.com/PuerkitoBio/goquery"
	"strings"
)

var ParseMap = map[int]ContextParse{}

type ContextParse struct {
	Selector  string
	ParseFunc func(s *goquery.Selection) string
}

func InitRequestContextParse() {
	// 解析层级
	ParseMap[1] = ContextParse{Selector: "tr .provincetr td:has(a)", ParseFunc: ParseFunc}
	ParseMap[2] = ContextParse{Selector: "tr .citytr td:first-child", ParseFunc: ParseFunc}
	//ParseMap[3] = ContextParse{Selector: "tr .countytr td:first-child", ParseFunc: ParseFunc}
	//ParseMap[4] = ContextParse{Selector: "tr .towntr td:first-child", ParseFunc: ParseFunc}
}

func ParseFunc(s *goquery.Selection) string {
	href, _ := s.Find("a").Attr("href")
	return href
}

func (c *Context) ContextParseChild() []Context {
	cp := ParseMap[c.Level]
	if cp.Selector == "" {
		return nil
	}
	pc := parse.Context{}
	pc.LoadFile(c.Path)
	pc.Parse()
	doc := pc.GetDoc()
	find := doc.Find(cp.Selector)
	size := find.Size()
	if size == 0 {
		return nil
	}
	child := make([]Context, size)
	find.Each(func(i int, s *goquery.Selection) {
		href := cp.ParseFunc(s)
		cc := Context{}
		cc.SetLevel(c.Level)
		cc.SetUrl(constant.BaseUrl, href, c.Url)
		child[i] = cc
	})
	return child
}

func (c *Context) SetUrlParse(indexUrl string, pu string) string {
	switch c.Level {
	case 1:
		return indexUrl
	case 2:
		return indexUrl
	case 3:
		return indexUrl
	case 4:
		pp := getLastPath(pu)
		indexUrl = pp + "/" + indexUrl
		return indexUrl
	case 5:
		url1 := pu[:strings.LastIndex(pu, "/")]
		p1 := url1[strings.LastIndex(url1, "/")+1:]
		url1 = url1[:strings.LastIndex(url1, "/")]
		p2 := url1[strings.LastIndex(url1, "/")+1:]
		return p2 + "/" + p1 + "/" + indexUrl
	default:
		return indexUrl
	}
}

func getLastPath(url string) string {
	url1 := url[:strings.LastIndex(url, "/")]
	pp := url1[strings.LastIndex(url1, "/")+1:]
	return pp
}
